import _ from 'lodash';

// config/config-manager.js
class ConfigManager {
  constructor() {
    this.config = {}
    this.nacosClient = null
  }

  async init(appId) {
    // 从Nacos获取配置
    const remoteConfig = await this.fetchFromNacos(appId)
    console.log("🚀 ~ config-manager.js:13 ~ ConfigManager ~ init ~ remoteConfig:", remoteConfig)
    const localConfig = this.getLocalConfig()

    this.config = {
      // ...this.getDefaultConfig(),
      ...localConfig,
      ...remoteConfig
    }

    return this.config
  }
  getLocalConfig(){
    return {
      nacosBaseUrl:"http://127.0.0.1:8848/nacos"
    }
  }
  async fetchFromNacos(appId) {
    console.log("🚀 ~ config-manager.js:30 ~ ConfigManager ~ fetchFromNacos ~ appId:", appId)
    try {
      // const response = await fetch(`${this.config.nacosBaseUrl}/v2/cs/config`, {
      const response = await fetch(`${process.env.VUE_APP_NACOS_SERVER}/nacos/v2/cs/config?dataId=${appId}&group=DEFAULT_GROUP`)
      return await response.json()
    } catch (error) {
      console.warn('Nacos配置获取失败，使用本地配置:', error)
      return {}
    }
  }

  get(key, defaultValue = null) {
    return _.get(this.config, key, defaultValue)
  }

  set(key, value) {
    _.set(this.config, key, value)
  }
}

export default new ConfigManager()